package baptizeattribute.utils;

import baptizeattribute.inventory.Inv;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.List;
import java.util.Random;

public class Tools {

    /**
     * 给予玩家指定物品的指定数量
     * @param p
     * @param itemStack
     * @param num
     * @return 返回是否给予成功
     */
    public static boolean addPlayerByItem(Player p, ItemStack itemStack, int num){
        boolean flag = false;
        for (int i = 0 ; i < 36 ; i++) {
            if (p.getInventory().getItem(i) == null)
            {
                itemStack.setAmount(num);
                p.getInventory().setItem(i, itemStack);
                flag = true;
                break;
            }else if (p.getInventory().getItem(i).isSimilar(itemStack) && itemStack.getMaxStackSize()!=1){
                int amount = p.getInventory().getItem(i).getAmount();
                int a = amount+num;
                if (amount+num>64){
                    a=64;
                    num=num-(64-amount);
                    itemStack.setAmount(a);
                    p.getInventory().setItem(i, itemStack);
                }else {
                    itemStack.setAmount(a);
                    p.getInventory().setItem(i, itemStack);
                    flag = true;
                    break;
                }
            }
        }
        if (!flag){
            itemStack.setAmount(num);
            p.getWorld().dropItem(p.getLocation(),itemStack);
            flag = true;
        }
        return flag;
    }

    /**
     * 判断物品是否是lore物品
     * @param itemStack
     * @return
     */
    public static boolean isItem(ItemStack itemStack){
        if (itemStack!=null&&itemStack.hasItemMeta()&&itemStack.getItemMeta().hasLore()){
            return true;
        }
        return false;
    }

    /**
     * 给容器里某个位置的物品替换Lore
     * @param iv 容器
     * @param num 位置
     * @param list Lore
     */
    public static void setItemLore(Inventory iv , int num, List<String> list){
        ItemStack item = iv.getItem(num);
        ItemMeta itemMeta = item.getItemMeta();
        itemMeta.setLore(list);
        item.setItemMeta(itemMeta);
        iv.setItem(num,item);
    }

    /**
     * 取两个数的随机值
     * @param min
     * @param max
     * @return
     */
    public static int getRandom(int min, int max){
        Random random = new Random();
        return random.nextInt(max-min+1)+min;
    }
}